package com.consumer.service.impl;

import com.consumer.config.LoginCachManaher;
import com.consumer.entity.Log;
import com.consumer.entity.User;
import com.consumer.mapper.LogMapper;
import com.consumer.service.LogService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.Objects;

/**
 * @Description
 * @Author youxin
 * @Version V1.0.0
 * @Since 1.0
 * @Date 2021/11/16
 */
@Service
public class LogServiceImpl implements LogService {
    @Autowired
    private LogMapper logMapper;
    @Autowired
    private LoginCachManaher loginCachManaher;
    @Autowired
    private RedisTemplate redisTemplate;

    @Override
    public void saveLog(Log log) {
        logMapper.saveLog(log);
        //TODO  数据落库的时候更新本地缓存 以及  redis缓存
        User user=new User();
        user.setId(log.getId());
        user.setUsername(log.getLoginName());
        user.setPassword("123456");
        loginCachManaher.saveLoginCach(user);
        //TODO 跟新redis缓存
        redisTemplate.opsForValue().set(log.getId(),user);
    }

    @Override
    public User getLoginList(String id) {
        //TODO 优先从jvm中获取数据
        User user = loginCachManaher.getLoginLog(id);
        if(!Objects.isNull(user)){
            return user;
        }
        //TODO 如果jvm缓存中没有数据 则从redis中获取
        user = (User) redisTemplate.opsForValue().get(id);
        if(!Objects.isNull(user)){
            return user;
        }
        // TODO 若果jvm 里面没有 查数据库
        Log log= logMapper.selectById(id);
        if(!Objects.isNull(log)){
            user.setId(id);
            user.setUsername(log.getLoginName());
            user.setPassword("12345");
        }
        return user;
    }
}
